import { asyncRoutes, constantRoutes } from '@/router'
import { getMenus } from '@/api/menu'
import { toTree } from '@/utils'
import Layout from '@/layout'

function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

// const loadView = (view) => { // 路由懒加载
//   return () => Promise.resolve(require(`@/views${view}`).default)
// }

// export function filterAsyncRoutes(routes, roles) {
//   const res = []
//   routes.forEach(route => {
//     const tmp = { ...route }
//     if (hasPermission(roles, tmp)) {
//       if (tmp.children) {
//         tmp.children = filterAsyncRoutes(tmp.children, roles)
//       }
//       res.push(tmp)
//     }
//   })
//   return res
// }

export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = {...route}
    if (hasPermission(roles, tmp)) {
      const component = tmp.component
      if (route.component) {
        if (component == 'Layout') {
          tmp.component = Layout
        } else {
          tmp.component = (resolve) => require([`@/views${component}`], resolve)
        }
        if (tmp.children) {
          tmp.children = filterAsyncRoutes(tmp.children, roles)
        }
      }
      res.push(tmp)
    }
  })
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({commit}, roles) {
    return new Promise(resolve => {
      getMenus({pageIndex: 1, pageSize: 1000}).then(response => {
        let accessedRoutes = filterAsyncRoutes(toTree(response.data.data.rows), roles)
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      })
    })
  },

  // generateRoutes({ commit }, roles) {
  //   return new Promise(resolve => {
  //     // 定义一个变量用来存放可以访问的路由表
  //     let accessedRoutes
  //     // 判断当前角色是否包含admin
  //     if (roles.includes('admin')) {
  //       // 所有路由都可以被访问，将anyncRoutes改造成从数据库中获取
  //       accessedRoutes = asyncRoutes || []
  //     } else {
  //       // 根据角色过滤掉不能访问的路由表
  //       accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
  //     }
  //     commit('SET_ROUTES', accessedRoutes)
  //     resolve(accessedRoutes)
  //   })
  // },

  // ------------------------
  // generateRoutes({ commit }, roles) {
  //   return new Promise(resolve => {
  //     // 先查询后台并返回左侧菜单数据并把数据添加到路由
  //     getMenus({ pageIndex: 1, pageSize: 1000 }).then(res => {
  //       if (res.code !== 200) {
  //         this.$message({
  //           message: '菜单数据加载异常',
  //           type: 'error'
  //         })
  //       } else {
  //         const data = toTree(res.data.data.rows)
  //         // const data = res.data.data.rows
  //         let accessedRoutes
  //         if (roles.includes('admin')) {
  //           // alert(JSON.stringify(asyncRoutes))
  //           accessedRoutes = asyncRoutes || []
  //         } else {
  //           accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
  //         }
  //         commit('SET_ROUTES', accessedRoutes)
  //         resolve(accessedRoutes)
  //       }
  //       // generaMenu(asyncRoutes, data)
  //     }).catch(error => {
  //     })
  //   })
  // },

  // generateRoutes: async function({commit}, roles){
  //   let res = await getMenus({ pageIndex: 1, pageSize: 1000 })
  //   let myAsyncRoutes = toTree(res.data.data.rows)
   
  //   myAsyncRoutes = myAsyncRoutes.filter(curr=>{
  //     if (curr.children == null || curr.children.length === 0) {
  //       delete curr.children
  //     }
  //     return replaceComponent(curr)
  //   })
  //   let accessedRoutes
  //   if (roles.includes('admin')) {
  //     accessedRoutes = myAsyncRoutes || []
  //   } else {
  //     accessedRoutes = filterAsyncRoutes(myAsyncRoutes, roles)
  //   }
  //   commit('SET_ROUTES', accessedRoutes)
  //   resolve(accessedRoutes)
  // }
}

// 替换route对象中的component
function replaceComponent(comp) {
  if (comp.component && typeof(comp.component) == 'string') {
    comp.component = componentMap[comp.component];
  }
  if (comp.children && comp.children.length>0) {
    for (let i = 0; i < comp.children.length; i++) {
      comp.children[i] = replaceComponent(comp.children[i])
    }
  }
  return comp
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
